import urllib

import aiohttp
import aioredis
import lxml.html
import json
import asyncio
import time
import random
import logging
import sys
import os
from faker import Faker
import base64
import re
# sys.path.append(os.path.abspath('../'))


logger = logging.getLogger("cmcc")

card = {'100': {'cardValCode': '04',
                'cardValue': '10000',
                'offerRate': '1',
                'offerRateId': ''},
        '20': {'cardValCode': '01',
               'cardValue': '2000',
               'offerRate': '1',
               'offerRateId': ''},
        '30': {'cardValCode': '02',
               'cardValue': '3000',
               'offerRate': '1',
               'offerRateId': ''},
        '300': {'cardValCode': '05',
                'cardValue': '30000',
                'offerRate': '1',
                'offerRateId': ''},
        '50': {'cardValCode': '03',
               'cardValue': '5000',
               'offerRate': '1',
               'offerRateId': ''}}

def get_ts():
    return str(time.time()).replace('.', '')[:13]

async def get_unicom_ali(user_tel, amount, upay_id, redis, ticket=''):
    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {'Cookie': 'upay_user=%s;' % upay_id, 'Host': 'upay.10010.com',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0',
               # "User-Agent": "Mozilla/5.0 (Linux; Android 7.0; MI 5s Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/64.0.3282.137 Mobile Safari/537.36 wxwork/2.4.16 MicroMessenger/6.3.22 NetType/WIFI Language/zh",
               'X-Requested-With': 'XMLHttpRequest',
               'Referer': 'http://upay.10010.com/npfwap/npfMobWap/bankcharge/index.html?version=wap&desmobile=6672070486447365',
               # 'CLIENT-IP': ip,
               # 'X-FORWARDED-FOR': ip,
               }

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info("代理%s|%s", user_tel, proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    # print(proxy)
    logger.info(conn)
    async with aiohttp.ClientSession(headers=headers) as session:
        prov_url = 'http://upay.10010.com/npfwap/npfMobWeb/getArea/init?callback=jQuery&commonBean.phoneNo=%s&_=%s' % (user_tel, get_ts())
        async with session.get(prov_url, proxy=conn, timeout=5) as rsp:
            body = await rsp.text()
            # print(body)
            area = re.findall('(\d+)', body)
            prov = body.split('X')[2]
        if not area:
            return {"code": -1, "message": rsp.content.decode()}
        card_info = card.get(str(amount), {})
        if card_info:
            bussine_type = '06'
            userChooseMode = '0'
            url = 'http://upay.10010.com/npfwap/NpfMob/mobWapBankCharge/wapBankChargeCheck.action'
            url2 = 'http://upay.10010.com/npfwap/NpfMob/mobWapBankCharge/wapBankChargeSubmit.action'
        else:
            bussine_type = '01'
            userChooseMode = ''
            url = 'http://upay.10010.com/npfwap/NpfMob/mobWapBankPay/mobWapPayFeeCheck.action'
            url2 = 'http://upay.10010.com/npfwap/NpfMob/mobWapBankPay/mobWapPayFeeApply.action'
        data = {
            'browserVersion': '',
            'bussineTypeInput': '0',
            'cardBean.cardValue': card_info.get('cardValue', ''),
            'cardBean.cardValueCode': card_info.get('cardValCode', ''),
            'channelKey': 'wxgz',
            'commonBean.activityType': '',
            'commonBean.areaCode': '',
            'commonBean.bussineType': bussine_type,
            'commonBean.channelCode': 'weixinH5',
            'commonBean.channelType': '307',
            'commonBean.cityCode': area[1],
            'commonBean.netAccount': '',
            'commonBean.offerate': card_info.get('offerRate', ''),
            'commonBean.offerateId': card_info.get('offerateId', ''),
            'commonBean.orgCode': '31',
            'commonBean.payAmount': amount,
            'commonBean.phoneNo': user_tel,
            'commonBean.provinceCode': area[0],
            'commonBean.reserved1': 'false',
            'commonBean.ticketNo': '',
            'commonBean.userChooseMode': userChooseMode,
            'invoiceBean.card_type': '',
            'invoiceBean.id_cardno': '',
            'invoiceBean.invoice_head': '',
            'invoiceBean.invoice_type': '',
            'invoiceBean.is_mailing': '0',
            'invoiceBean.need_invoice': '0',
            'numberType': '',
            'pointBean.payMethod': '',
            'pointBean.pointNumber': '',
            'ticketNew': ticket,
        }
        # print(data)

        async with session.post(url, data=data, headers=headers, proxy=conn) as rsp:
            res = await rsp.text()
            res = json.loads(res)
            logger.info(res)
            if res['out'] != 'success':
                # if res['out'] == "您的操作太频繁，请稍后再试！":
                #     await redis.srem("un_proxy", proxy)
                return {"code": -1, "message": res['out']}
            secstate = res['secstate']

        data2 = {'browserVersion': '',
                 'channelKey': '',
                 'commonBean.phoneNo': user_tel,
                 'commonBean.provinceCode': area[0],
                 'secstate.state': secstate,
                 'ticketNew': ticket}
        async with session.post(url2, data=data2, headers=headers, proxy=conn) as rsp:
            res = await rsp.text()
            # logger.info(res)
            res = json.loads(res)
            # print(res)
            pay_url = res['payUrl']

            # logger.info(pay_url)
        async with session.get(pay_url, proxy=conn) as rsp:
            # print(rsp.headers)
            # ali_url = rsp.headers['Location']
            body = await rsp.text()
            # logger.info(body)
            # print(body)
            # print(rsp.url)
            url = re.findall('"(weixin.*)"', body)
            # logger.info(url)
            query_url = re.findall('redirect_url="(.*)"', body)[0]
            # print(query_url)
            # logger.info(url)
            # query_url = query_url.replace("%22", "")
        async with session.post(query_url, headers=headers, proxy=conn) as rsp:
            text = await rsp.text()
            # print(text)
            root = lxml.html.fromstring(text)
            ele = root.xpath('/html/body/div/a[1]')[0]
            # query_url = '%s/%s' % (os.path.split(str(rsp.url))[0], ele.attrib['href'])
            p = urllib.parse.urlparse(str(rsp.url))
            query_url = '%s://%s%s/%s' % (p.scheme, p.hostname, os.path.split(p.path)[0], ele.attrib['href'])
            print({"code": 0, "url": url[0], "query_url": query_url})
            return {"code": 0, "url": url[0], "query_url": query_url, "prov": prov}


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    now = time.time()
    redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
    task = asyncio.ensure_future(get_unicom_ali("18690287979", "1", "12291d29f3542ec14b87c443ca2ee634", redis, 'l-mECQiF39Zasa3vLlarEaNAXPcCNB2c_oDg82ildYwFjHonAuJYFvDe54VbC3rMgyr2i9A2GYg*'))
    # task = asyncio.ensure_future(cmcc_query("322018111618325377201158463", "13871137387", ""))
    print(loop.run_until_complete(task))
    print(time.time() - now)
    loop.close()
